﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Web.Mvc;
using System.Xml.Linq;
using Xenta.Attributes;
using Xenta.Utils;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.System.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class ReportController : ExtController
    {
        [HttpGet, RestoreState]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, PersistState]
        public ActionResult Report(string name, 
            IDictionary<String, String> properties,
            string returnUrl)
        {
            try
            {
                long rptElapsedTime = 0;
                string rptMimeType = String.Empty;
                var rptData = Svc.BuildReport(name, 
                    properties, 
                    out rptMimeType, 
                    out rptElapsedTime);
                string dwlExt = MimeTypeHelper.TypeToExt(rptMimeType);
                string dwlName = String.Format("{0}.{1}", name, dwlExt);
                return File(rptData, rptMimeType, dwlName);
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            if(!String.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction(Loc.Act("Index"));
        }

        [ChildActionOnly]
        public ActionResult Render(string name, 
            Dictionary<String, String> properties, 
            bool cacheAllowed = false)
        {
            dynamic m = (cacheAllowed ? HttpContext.Cache.Get(name) : null) 
                as ExpandoObject;
            if(m == null)
            {
                m = new ExpandoObject();
                try
                {
                    long rptElapsedTime = 0;
                    string rptMimeType = String.Empty;
                    var rptData = Svc.BuildReport(name, 
                        properties, 
                        out rptMimeType, 
                        out rptElapsedTime);
                    if(!rptMimeType.Equals("text/xml"))
                    {
                        rptData.Dispose();
                        return new EmptyResult();
                    }
                    m.ElapsedTime = rptElapsedTime;
                    m.Data = XElement.Load(rptData);
                    if(cacheAllowed)
                        HttpContext.Cache.Insert(name, m);
                }
                catch
                {
                    return new EmptyResult();
                }
            }
            return PartialView(String.Format("_{0}", name), m);
        }
    }
}
